'''
Created on 22.05.2013

@author: MathiasAr
'''

import socket
from array import array 
from sys import argv
from sys import exit
from os.path import split
from os import popen
from time import sleep
from pyping import pyping

_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

if __name__ == '__main__':
    usage = "%s -mac 00-01-05-0F-92-8D -ip 169.254.1.158" % split(argv[0])[1]
    
    argmac = None
    macs = []
    
    if "-mac" in argv:
        i = argv.index("-mac")
        if i+1 < len(argv):
            mac = str(argv[i+1]).replace('-', '').strip()
            if len(mac) == 12:
                argmac = [int(mac[i:i+2],16) for i in range(0,len(mac), 2)]
            else:
                print usage
                print "\nWrong MAC address"
                exit(1)
            pass
        else:
            print usage
            print "\nMissing MAC address"
            exit(2)
    else:
        print usage
        print "\nMissing MAC address argument"
        exit(3)
    
    argip = None
    
    if "-ip" in argv:
        i = argv.index("-ip")
        if i+1 < len(argv):
            ip = str(argv[i+1]).strip()
            if len(ip.split('.')) == 4:
                argip = ip
            else:
                print usage
                print "\nWrong IP address"
                exit(4)
            pass
        else:
            print usage
            print "\nMissing IP address"
            exit(5)
    else:
        print usage
        print "\nMissing IP address argument, using Localnet (127.255.255.255) address"
        argip = "127.255.255.255"
    
    
    arr = array('B')
    for i in range(0,6):
        arr.append(0xff)
    
    for i in range(0,16):
        arr.fromlist(argmac)
    
    _socket.sendto(arr.tostring(),(argip, 65535))
    _socket.close()
    
    print "Send WakeOnMagic(R)"
    
    macs = "-".join(["%.2x" % (argmac[i]) for i in range(0,len(argmac))])
    
    while(1):
        
        sleep(2)
        
        # try to ping IP address
        print pyping().ping(argip, 2, 1)
        
        
        exit(0)
    
    pass